package com.xiaozhi.config;

import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import jakarta.annotation.PostConstruct;

/**
 * Debug配置类，用于验证LangChain4j Bean的注入状态
 */
@Configuration
public class DebugConfig {
    
    private static final Logger log = LoggerFactory.getLogger(DebugConfig.class);
    
    @Autowired(required = false)
    private ChatLanguageModel openAiChatModel;
    
    @Autowired(required = false)
    private EmbeddingModel embeddingModel;
    
    @Autowired
    private Environment environment;
    
    /**
     * 应用启动时验证必要的环境变量
     */
    @PostConstruct
    public void validateConfiguration() {
        log.info("=== 环境变量验证开始 ===");
        
        // 检查是否在测试环境中运行
        String[] activeProfiles = environment.getActiveProfiles();
        boolean isTestEnvironment = false;
        for (String profile : activeProfiles) {
            if ("test".equals(profile)) {
                isTestEnvironment = true;
                break;
            }
        }
        
        if (isTestEnvironment) {
            log.info("🧪 检测到测试环境，跳过环境变量验证");
            return;
        }
        
        // 检查是否在开发环境中运行（没有设置profile或者是dev profile）
        boolean isDevelopmentEnvironment = activeProfiles.length == 0;
        for (String profile : activeProfiles) {
            if ("dev".equals(profile) || "development".equals(profile)) {
                isDevelopmentEnvironment = true;
                break;
            }
        }
        
        String deepseekKey = System.getenv("DEEPSEEK_API_KEY");
        String dashscopeKey = System.getenv("DASHSCOPE_API_KEY");
        
        boolean hasErrors = false;
        
        if (!StringUtils.hasText(deepseekKey)) {
            if (isDevelopmentEnvironment) {
                log.warn("⚠️ DEEPSEEK_API_KEY 环境变量未设置，开发环境将使用Mock实现");
            } else {
                log.error("❌ DEEPSEEK_API_KEY 环境变量未设置或为空，这是生产环境必需的配置项");
                hasErrors = true;
            }
        } else {
            log.info("✅ DEEPSEEK_API_KEY 环境变量已正确设置");
        }
        
        if (!StringUtils.hasText(dashscopeKey)) {
            log.warn("⚠️ DASHSCOPE_API_KEY 环境变量未设置，文本向量化功能可能不可用");
        } else {
            log.info("✅ DASHSCOPE_API_KEY 环境变量已正确设置");
        }
        
        if (hasErrors) {
            String errorMessage = "必需的环境变量未配置，请设置 DEEPSEEK_API_KEY 环境变量后重启应用";
            log.error("❌ {}", errorMessage);
            throw new IllegalStateException(errorMessage);
        }
        
        log.info("=== 环境变量验证完成 ===");
    }
    
    /**
     * 应用启动完成后检查Bean状态
     */
    @EventListener(ApplicationReadyEvent.class)
    public void checkBeans() {
        log.info("=== LangChain4j Bean状态检查 ===");
        
        if (openAiChatModel != null) {
            log.info("✅ OpenAI Chat Model Bean注入成功: {}", openAiChatModel.getClass().getSimpleName());
            try {
                // 测试模型是否可用
                String testResponse = openAiChatModel.chat("Hello");
                log.info("✅ Chat Model测试成功，响应: {}", testResponse);
            } catch (Exception e) {
                log.error("❌ Chat Model测试失败: {}", e.getMessage());
            }
        } else {
            log.error("❌ OpenAI Chat Model Bean注入失败");
        }
        
        if (embeddingModel != null) {
            log.info("✅ Embedding Model Bean注入成功: {}", embeddingModel.getClass().getSimpleName());
        } else {
            log.warn("⚠️ Embedding Model Bean注入失败或未配置");
        }
        
        // 环境变量已在 @PostConstruct 方法中验证
        
        log.info("=== Bean状态检查完成 ===");
    }
}